<script setup>
import { ref, onMounted, onUpdated } from 'vue'
import { ElInput, ElButton, ElScrollbar, ElLoading } from 'element-plus'
import userApi from '../../api/user'

// 聊天消息列表
const messages = ref([
  { role: 'assistant', content: '你好！我是AI助手，有什么可以帮助你的吗？' }
])
// 输入框内容
const inputContent = ref('')
// 聊天窗口引用
const chatWindowRef = ref(null)
// 加载状态
const loading = ref(false)
// 对话ID，用于维护会话上下文
const conversationId = ref('student-' + Date.now())

// 发送消息
const sendMessage = () => {
  if (!inputContent.value.trim()) return

  // 添加用户消息
  messages.value.push({ role: 'user', content: inputContent.value })
  const userMessage = inputContent.value
  inputContent.value = ''
  loading.value = true

  // 添加一个空的AI回复占位符
  const aiMessageIndex = messages.value.length
  messages.value.push({ role: 'assistant', content: '' })

  // 调用后端API获取AI回复
  userApi.chatStream(
      userMessage,
      conversationId.value,
      // 接收流式数据回调
      (chunk) => {
        messages.value[aiMessageIndex].content += chunk
      },
      // 完成回调
      () => {
        loading.value = false
      },
      // 错误回调
      (error) => {
        console.error('AI聊天错误:', error)
        messages.value[aiMessageIndex].content = '抱歉，获取AI回复失败，请稍后重试。'
        loading.value = false
      }
  )
}

// 监听键盘事件
const handleKeyDown = (e) => {
  if (e.key === 'Enter' && !e.shiftKey && !loading.value) {
    e.preventDefault()
    sendMessage()
  }
}

// 滚动到最新消息
const scrollToBottom = () => {
  if (chatWindowRef.value) {
    chatWindowRef.value.scrollTo({ top: chatWindowRef.value.scrollHeight, behavior: 'smooth' })
  }
}

// 组件更新后滚动到底部
onUpdated(() => {
  scrollToBottom()
})

// 组件挂载后滚动到底部
onMounted(() => {
  scrollToBottom()
})
</script>

<template>
  <div class="chat-container">
    <div class="chat-header">
      <h3>AI聊天助手</h3>
    </div>
    <div class="chat-messages" ref="chatWindowRef">
      <ElScrollbar height="100%">
        <div v-for="(msg, index) in messages" :key="index" :class="['message', msg.role]">
          <div class="avatar">{{ msg.role === 'user' ? '我' : 'AI' }}</div>
          <div class="content">
            {{ msg.content }}
            <ElLoading v-if="loading && index === messages.length - 1" size="small" />
          </div>
        </div>
      </ElScrollbar>
    </div>
    <div class="chat-input">
      <ElInput
          v-model="inputContent"
          type="textarea"
          placeholder="请输入消息..."
          :rows="3"
          :disabled="loading"
          @keydown="handleKeyDown"
      />
      <ElButton type="primary" @click="sendMessage" :loading="loading">发送</ElButton>
    </div>
  </div>
</template>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 800px; /* 固定高度 */
  width: 800px; /* 固定宽度 */
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  margin: 20px auto;
}

.chat-header {
  padding: 12px 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow: hidden; /* 防止内容溢出 */
  background-color: #fff;
}

.message {
  display: flex;
  margin-bottom: 16px;
  max-width: 80%;
}

.message.user {
  flex-direction: row-reverse;
  margin-left: auto;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  flex-shrink: 0;
}

.message.user .avatar {
  background-color: #67c23a;
  margin-right: 0;
  margin-left: 10px;
}

.content {
  padding: 10px 14px;
  border-radius: 8px;
  background-color: #f5f7fa;
  word-break: break-word;
  position: relative;
}

.message.user .content {
  background-color: #409eff;
  color: white;
}

.chat-input {
  padding: 16px;
  border-top: 1px solid #e4e7ed;
  background-color: #f5f7fa;
}

.el-input {
  margin-bottom: 10px;
}
</style>